import {Menu, MenuProps} from "antd";
import {AppstoreOutlined, MailOutlined, UserOutlined, AreaChartOutlined} from '@ant-design/icons';
import {useEffect, useMemo, useState} from "react";
import {useLocation, useNavigate} from "react-router-dom";
import {useAppSelector, useDictCategory} from "../../Hooks";
import {RootState} from "../../store";

type MenuItem = Required<MenuProps>['items'][number];

// 公共menu
const MyMenu = () => {
    // 当前路由信息
    const l = useLocation();
    // 选中key
    const [selectedKeys, setSelectedKeys] = useState<Array<string>>([l.pathname]);
    // 跳转
    const n = useNavigate();
    // 分类hooks
    const {menu} = useDictCategory();
    // info,获取权限信息
    const infoData = useAppSelector((state: RootState) => state.info);
    // 展开项
    const openKeys = useMemo(() => {
        const pathname = l.pathname;
        const startIndex = pathname.indexOf("/");
        const endIndex = pathname.indexOf("/", 2);
        return [pathname.substring(startIndex, endIndex)];
    }, [menu])

    function getItem(
        label: React.ReactNode,
        key?: React.Key | null,
        icon?: React.ReactNode,
        children?: MenuItem[],
        type?: 'group',
    ): MenuItem {
        return {
            key,
            icon,
            children,
            label,
            type,
        } as MenuItem;
    }

    // menu点击
    const menuClick = ({key}: { key: string }) => {
        n(key);
        setSelectedKeys([key]);
    }

    const [items, setItems] = useState<MenuItem[]>([
        getItem('首页', '/home', <MailOutlined/>),
        getItem('数据字典', '/dict', <AppstoreOutlined/>),
        getItem('用户管理', '/user', <UserOutlined/>),
    ]);

    // 渲染子项
    const getChild = (child: Array<{ id: string, type_id: string, name: string }> | undefined, name: string) => {
        const childItem: MenuItem[] = [];
        for (const v of child ?? []) {
            childItem.push(getItem(v.name, getKey(name) + '/' + v.id))
        }
        return childItem;
    }

    // key判断
    const getKey = (name: string) => {
        let key = '';
        switch (name) {
            case "文献管理":
                key = '/literature'
                break;
            case "文章管理":
                key = '/article'
                break;
            default:
                key = '/region'
                break;
        }
        return key;
    }

    // 是否拥有权限
    const isJurisdiction = (name: string) => infoData.jurisdictions.findIndex(v => v.name === name) >= 0

    // 权限逻辑
    useEffect(() => {
        const menuItem: MenuItem[] = [
            getItem('首页', '/home', <MailOutlined/>)
        ]
        if (infoData.id) {
            if (isJurisdiction("用户管理")) {
                menuItem.push(getItem('用户管理', '/user', <UserOutlined/>),);
            }
            if (isJurisdiction("数据字典")) {
                menuItem.push(getItem('数据字典', '/dict', <AppstoreOutlined/>));
            }
        }
        setItems(menuItem)
    }, [infoData])

    // 加载菜单和子菜单
    useEffect(() => {
        const menuItem: MenuItem[] = [];
        for (const v of menu) {
            if (v.child?.length ?? 0 > 0) {
                menuItem.push(getItem(v.name, getKey(v.name), <AreaChartOutlined/>, getChild(v.child, v.name)));
            }
        }
        setItems(v => [...v, ...menuItem]);
    }, [menu])

    return (
        <Menu
            defaultOpenKeys={openKeys}
            theme="dark"
            onClick={menuClick}
            style={{width: "100%", height: "calc(100vh - 70px)"}}
            selectedKeys={selectedKeys}
            mode="inline"
            items={items}
        />
    )
}

export default MyMenu;